package com.iuie.ns.frame.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.iuie.ns.frame.exception.FileDownloadException;
import com.iuie.ns.frame.free.excel.beans.SheetColumn;

/**
 * 导出CSV文件工具类
 * @author iuie
 * @date 2018年5月31日下午3:08:08
 */
public class CSVUtils {

	/**
	 * 导出csv文件的实现方法
	 * @param os
	 * @param clazz
	 * @param lst
	 * @param pattern
	 * @author iuie
	 * @date 2018年5月31日 下午3:17:10
	 */
	public static <T> void export(OutputStream os, Class<?> clazz, List<T> lst, String pattern) {
		String s = exportToString(clazz, lst, pattern);
		ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes());
		try {
			byte[] buffer = new byte[1024];
			
			int len = 0;
			while((len = bais.read(buffer)) != -1 ) {
				os.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new FileDownloadException("", "导出csv文件失败！");
		} finally {
			try {
				if (os != null) {
					os.flush();
					os.close();
				}
				if (bais != null) {
					bais.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 导出输入流InputStream
	 * @param clazz
	 * @param lst
	 * @param pattern
	 * @return
	 * @author iuie
	 * @date 2018年6月5日 下午4:13:15
	 */
	public static <T> InputStream exportInputStream(Class<?> clazz, List<T> lst, String pattern) {
		String s = exportToString(clazz, lst, pattern);
		return new ByteArrayInputStream(s.getBytes());
	}
	
	public static <T> String exportToString(Class<?> clazz, List<T> lst, String pattern) {
		List<SheetColumn> headers = SheetColumnUtils.getSheetColumns(clazz);
		if (ListUtils.isEmpty(headers)) {
			throw new FileDownloadException("", "导出csv文件失败，没有具体的数据列！");
		}
		
		StringBuilder sb = new StringBuilder(12);
		// 写入表头
		for (SheetColumn col: headers) {
			String name = col.getColumnName();
			sb.append("\"").append(name).append("\",");
		}
		sb.append("\n");
		
		try {
			// 数据为空时，退出
			if (ListUtils.isEmpty(lst)) {
				return sb.toString();
			}
			// 遍历数据
			Iterator<T> it = lst.iterator();
			while (it.hasNext()) {
				T obj = it.next();
				if (obj == null) {
					continue;
				}
				for (int i = 0; i < headers.size(); i++) {
					String getMethodName = headers.get(i).getMethodNameByColumnKey();
					Class<? extends Object> tCls = obj.getClass();
					Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
					Object value = getMethod.invoke(obj, new Object[] {});
					// 判断值的类型后进行强制类型转换
					String textValue = null;
					if (value != null) {
						if (value instanceof String || value instanceof Integer || value instanceof Double || value instanceof Float) {
							textValue = String.valueOf(value);
						} else if (value instanceof Date) {
							Date date = (Date) value;
							SimpleDateFormat sdf = new SimpleDateFormat(pattern);
							textValue = sdf.format(date);
						} else {
							textValue = value.toString();
						}
					}
					// 拼接
					sb.append("\"").append(textValue).append("\",");
				}
				sb.append("\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new FileDownloadException("", "导出csv文件失败！");
		}
		return sb.toString();
	}
}
